import os
from aerich import Command
from fastapi import FastAPI
from tortoise.contrib.fastapi import register_tortoise

from settings import load_env, config
from routers import router_root

app = FastAPI(title=load_env.TITLE,
              version=load_env.VERSION)
app.include_router(router_root)


@app.on_event("startup")
async def startup():
    print("启动数据平台")
    register_tortoise(
        app,
        config=config.TORTOISE_ORM,
        generate_schemas=False,
        add_exception_handlers=True,
    )


@app.on_event("startup")
async def aerich_database():
    """数据库迁移
    aerich init -t settings.config.TORTOISE_ORM
    aerich init-db
    """
    command = Command(tortoise_config=config.TORTOISE_ORM)
    await command.init()
    await command.migrate()
    await command.upgrade(run_in_transaction=True)
    print("数据库启动成功")


if __name__ == '__main__':
    import uvicorn

    uvicorn.run('main:app', host='127.0.0.1', port=9999, reload=True)
